<template>
  <div class="login-container">
    <!-- 未登录状态显示登录图标 -->
    <el-button v-if="!isLoggedIn" class="login-button" @click="showLoginDialog" type="primary" circle>
      <el-icon>
        <User />
      </el-icon>
    </el-button>
    
    <!-- 已登录状态显示用户头像 -->
    <el-dropdown v-else trigger="click">
      <el-avatar :size="40" :src="userInfo.avatar || defaultAvatar" class="user-avatar" />
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item disabled>
            <div class="user-dropdown-info">
              <span class="username">{{ userInfo.name }}</span>
            </div>
          </el-dropdown-item>
          <el-dropdown-item divided @click="goToUserCenter">
            <el-icon>
              <User />
            </el-icon>
            <span>个人中心</span>
          </el-dropdown-item>
          <el-dropdown-item @click="logout">
            <el-icon>
              <SwitchButton />
            </el-icon>
            <span>退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <!-- 登录/注册对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="400px" align-center>
      <div class="auth-container">
        <el-tabs v-model="activeTab" class="auth-tabs" @tab-change="resetForm">
          <el-tab-pane label="登录" name="login">
            <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" status-icon @keyup.enter="submitLoginForm">
              <el-form-item prop="username">
                <el-input v-model="loginForm.username" placeholder="用户名/邮箱">
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="loginForm.password" type="password" placeholder="密码" show-password>
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" class="submit-btn" :loading="loading" @click="submitLoginForm">
                  登录
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <el-tab-pane label="注册" name="register">
            <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" status-icon @keyup.enter="submitRegisterForm">
              <el-form-item prop="name">
                <el-input v-model="registerForm.name" placeholder="昵称">
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="username">
                <el-input v-model="registerForm.username" placeholder="用户名">
                  <template #prefix>
                    <el-icon><UserFilled /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="email">
                <el-input v-model="registerForm.email" placeholder="邮箱">
                  <template #prefix>
                    <el-icon><Message /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="registerForm.password" type="password" placeholder="密码" show-password>
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="confirmPassword">
                <el-input v-model="registerForm.confirmPassword" type="password" placeholder="确认密码" show-password>
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" class="submit-btn" :loading="loading" @click="submitRegisterForm">
                  注册
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { User, Lock, Message, UserFilled, SwitchButton } from '@element-plus/icons-vue'
import { login, register } from '../api/user.js'
import { useTokenStore, useUserStore } from '../stores/index'
import { useRoute, useRouter } from 'vue-router'

// 状态管理
const tokenStore = useTokenStore()
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()

// 检查登录状态
const isLoggedIn = computed(() => !!tokenStore.token)
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
// 使用Pinia中的用户信息
const userInfo = computed(() => userStore.userInfo)

// 初始化时获取用户信息
onMounted(async () => {
  if (tokenStore.token) {
    await userStore.fetchUserInfo()
  }
})

// 监听token变化，当token变化时重新获取用户信息
watch(() => tokenStore.token, async (newToken) => {
  if (newToken) {
    await userStore.fetchUserInfo()
  } else {
    userStore.clearUserInfo()
  }
})

// 对话框状态
const dialogVisible = ref(false)
const activeTab = ref('login')
const loading = ref(false)
const dialogTitle = computed(() => activeTab.value === 'login' ? '账号密码登录' : '注册新账号')

// 表单引用
const loginFormRef = ref(null)
const registerFormRef = ref(null)

// 登录表单数据
const loginForm = ref({
  username: '',
  password: ''
})

// 注册表单数据
const registerForm = ref({
  name: '',
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 密码验证 - 检查两次输入是否一致
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.value.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

// 登录表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名/邮箱', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 注册表单验证规则
const registerRules = {
  name: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass, trigger: 'blur' }
  ]
}

// 显示登录对话框
const showLoginDialog = () => {
  dialogVisible.value = true
  activeTab.value = 'login'
}

// 重置表单
const resetForm = () => {
  if (activeTab.value === 'login') {
    loginFormRef.value?.resetFields()
  } else {
    registerFormRef.value?.resetFields()
  }
}

// 延迟执行页面跳转，确保消息显示
const delayedRedirect = (message, delay = 500) => {
  ElMessage.success(message)
  setTimeout(() => {
    window.location.href = route.fullPath
  }, delay)
}

// 提交登录表单
const submitLoginForm = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const res = await login(loginForm.value)
        if (res.code === 200) {
          // 保存 token
          tokenStore.setToken(res.data.token)
          // 获取用户信息
          await userStore.fetchUserInfo()
          dialogVisible.value = false
          // 先显示消息，延迟后再跳转
          delayedRedirect('登录成功')
        } else {
          ElMessage.error(res.msg || '登录失败，请检查用户名和密码')
        }
      } catch (error) {
        console.error('登录出错:', error)
        ElMessage.error('登录失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 提交注册表单
const submitRegisterForm = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 创建注册数据对象，不包含确认密码字段
        const registerData = {
          name: registerForm.value.name,
          username: registerForm.value.username,
          password: registerForm.value.password,
          email: registerForm.value.email
        }
        
        const res = await register(registerData)
        if (res.code === 200) {
          ElMessage.success('注册成功，请登录')
          activeTab.value = 'login'
          resetForm()
        } else {
          ElMessage.error(res.msg || '注册失败，请稍后重试')
        }
      } catch (error) {
        console.error('注册出错:', error)
        ElMessage.error('注册失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 前往个人中心
const goToUserCenter = () => {
  router.push(`/user/${userInfo.value.id}`)
}

// 退出登录
const logout = () => {
  tokenStore.removeToken()
  userStore.clearUserInfo()
  // 先显示消息，延迟后再跳转
  delayedRedirect('已退出登录')
}
</script>

<style scoped>
.login-container {
  display: flex;
  align-items: center;
}

.login-button {
  font-size: 16px;
  transition: transform 0.2s;
}

.login-button:hover {
  transform: scale(1.05);
}

.user-avatar {
  cursor: pointer;
  transition: transform 0.2s;
  border: 2px solid var(--color-primary);
}

.user-avatar:hover {
  transform: scale(1.05);
}

.user-dropdown-info {
  display: flex;
  align-items: center;
  padding: 5px 0;
}

.username {
  font-weight: 500;
  margin-left: 5px;
}

.auth-container {
  padding: 10px;
}

.auth-tabs {
  width: 100%;
}

.submit-btn {
  width: 100%;
  margin-top: 10px;
}

:deep(.el-tabs__nav) {
  width: 100%;
  display: flex;
}

:deep(.el-tabs__item) {
  flex: 1;
  text-align: center;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-form-item:last-child) {
  margin-bottom: 0;
}
</style>

